//
// Created by yunnan xu on 2020/11/21.
//

#include "MobileInput.h"
#include "EngineCore.h"
#include <cmath>

static int sensitivity_pixel = 100;

void MobileInputMgr::OnAInputEvent(const AInputEvent* event)
{
    int touch_count = AMotionEvent_getPointerCount(event);

    // LOGI("OnAInputEvent AKeyEvent_getAction = %d", AKeyEvent_getAction(event));
    if (AKeyEvent_getAction(event) & AMOTION_EVENT_ACTION_UP)
    {
        if(cancelFunc) cancelFunc();
        return;
    }

    if (touch_count == 1)
    {
        float rawx = AMotionEvent_getRawX(event, 0);
        float rawy = AMotionEvent_getRawY(event, 0);
        float hisx = AMotionEvent_getHistoricalRawX(event, 0, 0);
        float hisy = AMotionEvent_getHistoricalRawY(event, 0, 0);

        if(diffXFunc) {
            if (rawx - hisx < sensitivity_pixel && rawx - hisx > -sensitivity_pixel) {
                diffXFunc(rawx - hisx);
            }
        }

        if (diffYFunc) {
            if (rawy - hisy < sensitivity_pixel && rawy - hisy>- sensitivity_pixel) {
                diffYFunc(rawy - hisy);
            }
        }
    }
    else if (touch_count == 2)
    {
        if (zoomFunc) {
            float rawx1 = AMotionEvent_getRawX(event, 0);
            float rawy1 = AMotionEvent_getRawY(event, 0);

            float rawx2 = AMotionEvent_getRawX(event, 1);
            float rawy2 = AMotionEvent_getRawY(event, 1);

            float hisx1 = AMotionEvent_getHistoricalRawX(event, 0, 0);
            float hisy1 = AMotionEvent_getHistoricalRawY(event, 0, 0);

            float hisx2 = AMotionEvent_getHistoricalRawX(event, 1, 0);
            float hisy2 = AMotionEvent_getHistoricalRawY(event, 1, 0);

            float centerx = (rawx1 + rawx2) * 0.5;
            float centery = (rawy1 + rawy2) * 0.5;

            float dist_now = sqrt(
                    (rawx1 - rawx2) * (rawx1 - rawx2) + (rawy1 - rawy2) * (rawy1 - rawy2));
            float dist_his = sqrt(
                    (hisx1 - hisx2) * (hisx1 - hisx2) + (hisy1 - hisy2) * (hisy1 - hisy2));

            if (dist_his < 1E-5) {
                zoomFunc(centerx, centery, 0);
            } else {
                zoomFunc(centerx, centery, dist_now / dist_his);
            }
        }
    }
}

void MobileInputMgr::SetOnDiffX(std::function<void(float)> diff_x_func)
{
    diffXFunc = diff_x_func;
}


void MobileInputMgr::SetOnDiffY(std::function<void(float)> diff_y_func)
{
    diffYFunc = diff_y_func;
}

void MobileInputMgr::SetOnZoom(std::function<void(float, float, float)> zoom_func)
{
    zoomFunc = zoom_func;
}

void MobileInputMgr::SetOnCancel(std::function<void()> cancel_func)
{
    cancelFunc = cancel_func;
}
